# -*- coding: utf-8 -*-

import base64
import logging
from odoo import http
from odoo.http import request, Response

_logger = logging.getLogger(__name__)


class FileShareController(http.Controller):

    @http.route('/file/download/<string:token>', type='http', auth='public', methods=['GET'], csrf=False)
    def download_file(self, token, **kwargs):
        """
        公开下载文件接口
        无需登录验证，通过唯一令牌下载文件
        """
        try:
            # 获取文件记录
            FileUpload = request.env['file.upload']
            file_record = FileUpload.get_file_by_token(token)
            
            if not file_record:
                _logger.warning(f"文件下载失败: 令牌 {token} 无效或文件不可用")
                return Response(
                    '<h1>文件不存在或已过期</h1><p>请检查下载链接是否正确，或联系文件提供者。</p>',
                    status=404,
                    content_type='text/html; charset=utf-8'
                )
            
            # 增加下载计数
            file_record.increment_download_count()
            
            # 解码文件数据
            file_content = base64.b64decode(file_record.file_data)
            
            # 构建响应头
            headers = [
                ('Content-Type', file_record.file_type or 'application/octet-stream'),
                ('Content-Disposition', f'attachment; filename="{file_record.name}"'),
                ('Content-Length', str(len(file_content))),
            ]
            
            _logger.info(f"文件下载成功: {file_record.name} (令牌: {token}), 下载次数: {file_record.download_count}")
            
            return Response(
                file_content,
                status=200,
                headers=headers
            )
            
        except Exception as e:
            _logger.error(f"文件下载异常: {str(e)}", exc_info=True)
            return Response(
                '<h1>服务器错误</h1><p>下载文件时发生错误，请稍后重试。</p>',
                status=500,
                content_type='text/html; charset=utf-8'
            )

    @http.route('/file/info/<string:token>', type='json', auth='public', methods=['POST'], csrf=False)
    def get_file_info(self, token, **kwargs):
        """
        获取文件信息接口（JSON API）
        无需登录验证
        """
        try:
            FileUpload = request.env['file.upload']
            file_record = FileUpload.get_file_by_token(token)
            
            if not file_record:
                return {
                    'success': False,
                    'error': '文件不存在或不可访问'
                }
            
            return {
                'success': True,
                'data': {
                    'name': file_record.name,
                    'size': file_record.file_size,
                    'size_human': file_record._get_human_readable_size(),
                    'type': file_record.file_type,
                    'description': file_record.description,
                    'download_count': file_record.download_count,
                    'upload_date': file_record.create_date.isoformat() if file_record.create_date else None,
                    'expiry_date': file_record.expiry_date.isoformat() if file_record.expiry_date else None,
                }
            }
            
        except Exception as e:
            _logger.error(f"获取文件信息异常: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': '服务器错误'
            }

